package com.ruoyi.DingDing.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.DingDing.Domain.DingCallbackCrypto;
import com.ruoyi.common.core.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Map;


@RestController
@RequestMapping("/dingding")
public class DingDingController extends BaseController {
    private static final String AES_KEY = "MSMPEd8zdjG4p6RRnXfstzJ9FskbhrJVzzkE5NyYTzn";
    private static final String TOKEN = "Wou77vhiQbW3Jan";

    private static final String OWNER_KEY = "dinguz8ebdfa6kif1kz8";
    /**
     * 验证网址
     *
     * @return
     */
    @PostMapping("/list")
    public Object test (HttpServletRequestWrapper request) throws Exception {
        String requestJson = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        System.out.println("钉钉回调的完整信息："+JSON.toJSON(requestJson));
// 1. 从http请求中获取加解密参数
        String msg_signature = request.getParameter("msg_signature");
        if (msg_signature == null) {
            msg_signature = request.getParameter("signature");
        }
        String timeStamp = request.getParameter("timeStamp");
        if (timeStamp == null) {
            timeStamp = request.getParameter("timestamp");
        }
        String nonce = request.getParameter("nonce");

        JSONObject bodyJson = JSON.parseObject(requestJson);
        String encrypt = bodyJson.getString("encrypt");

        // 2. 使用加解密类型 事件订阅使用app_key
        DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(TOKEN, AES_KEY, OWNER_KEY);
        final String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encrypt);

        // 3. 反序列化回调事件json数据
        JSONObject eventJson = JSON.parseObject(decryptMsg);
        String eventType = eventJson.getString("EventType");

        // 4. 根据EventType分类处理
        if ("check_url".equals(eventType)) {
            // 测试回调url的正确性
        } else if ("user_add_org".equals(eventType)) {
            // 处理通讯录用户增加时间
        } else {
            // 添加其他已注册的
        }

        // 5. 返回success的加密数据
        Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
        System.out.println(successMap);
        return JSON.toJSON(successMap);
    }

}
